package com.lg.my.netty.codec;

import com.lg.consts.NettyConst;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * 探讨 netty 的编解码操作
 *
 * @author by Mr. Li 2021/4/22 2:12
 */
public class NettyServer {


    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup boosGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap().group(boosGroup, workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            final ChannelPipeline pipeline = socketChannel.pipeline();
                            //pipeline.addLast(new StringDecoder());
                            //pipeline.addLast(new ObjectDecoder(1024, ClassResolvers.cacheDisabled(null)));
                            pipeline.addLast(new ObjectDecodeByProtocl());

                            pipeline.addLast(new NettyServerHandler());
                        }
                    });

            System.out.println("NettyServer is starting....");
            final ChannelFuture channelFuture =
                    serverBootstrap.bind(NettyConst.ADDRESS_PORT).sync();
            channelFuture.channel().closeFuture().sync();

        } finally {
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
